<?php
namespace app\service;
use think\facade\Db;
use app\model\RoleModel;
use Exception;

class RoleService{  
    public function list(){
        $role = RoleModel::order('id','asc')->select(); 
        return $role;
    }

    public function rolePurviews($params){
        $role = Db::name('role')->where('id',$params['id'])->find();
        $rolePurviews = explode(",",$role['purviews']);  
        $purviews = Db::name('role_purview')->where('pid',0)->select();
        
        $tree=[];
        foreach ($purviews as $purview) {            
            $tmp=[];
            $tmp['title']=$purview['cn_name'];  
            $tmp['enName']=$purview['en_name'];  
            if(in_array($purview['en_name'],$rolePurviews)) {
                $tmp['checked'] = true;               
            }
            $children = Db::name('role_purview')->where('pid',$purview['id'])->select();
            if($children){
                foreach ($children as $child) { 
                    $ctmp=[];
                    $ctmp['title']=$child['cn_name'];  
                    $ctmp['enName']=$child['en_name'];     
                    if(in_array($child['en_name'],$rolePurviews)) {
                        $ctmp['checked'] = true;
                        $tmp['expand'] = true;
                    }           
                    $tmp['children'][] = $ctmp;
                }
            }  
            
            $tree[]=$tmp;          
        }
        
        return $tree;
    }

    public function save($params){    
        $data = RoleModel::where('role_name',$params['role_name'])->find();                 
        if(empty($params['id'])){  
            if($data){
                throw new Exception("角色已存在");
            }          
            $data = RoleModel::create($params); 
        }else{
            if($data && $data['id']!=$params['id']){
                throw new Exception("用户已存在");
            }
            $data = RoleModel::update($params, ['id' => $params['id']]); 
        }        
        return $data;
    }

    public function delete($params){   
        $data = RoleModel::destroy($params['id']);         
        return $data;
    }

    public function saveRolePurviews($params){
        $data = RoleModel::update(['purviews'=>$params['purviews']], ['id' => $params['id']]); 
        return $data;
    }
}